package cn.gogpay.duoim.sdk.network;

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.concurrent.TimeUnit;

public class IMHttpFactory {

    private static final Logger LOGGER = LoggerFactory.getLogger(IMHttpFactory.class);

    private static OkHttpClient okHttpClient;

    public static OkHttpClient client() {
        if (null == okHttpClient) {
            okHttpClient = defaultClient();
        }
        return okHttpClient;
    }

    public static void configClient(OkHttpClient client) {
        okHttpClient = client;
    }

    private static OkHttpClient defaultClient() {
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(message -> {
            try {
                String text = URLDecoder.decode(message, "utf-8");
                LOGGER.info("{}", text);
            } catch (UnsupportedEncodingException e) {
                LOGGER.error("{}", message, e);
            }
        });
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        return new OkHttpClient()
                .newBuilder()
                .connectTimeout(60, TimeUnit.SECONDS)
                .readTimeout(60, TimeUnit.SECONDS)
                .writeTimeout(60, TimeUnit.SECONDS)
                .addInterceptor(loggingInterceptor)
                .build();
    }
}
